<template>
  <el-container class="login-container">
    <el-main>
      <el-card class="login-card">
        <template #header>
          <div class="card-header">
            <h2>用户登录</h2>
          </div>
        </template>
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          label-width="80px"
          @submit.prevent="handleLogin"
        >
          <el-form-item label="用户名" prop="login_identifier">
            <el-input
              v-model="loginForm.login_identifier"
              placeholder="请输入用户名或邮箱"
              clearable
            />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              show-password
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" native-type="submit" :loading="loading">
              登录
            </el-button>
            <el-button @click="goToRegister">注册</el-button>
          </el-form-item>
          <el-form-item>
            <router-link to="/forgot-password">忘记密码？</router-link>
          </el-form-item>
        </el-form>
        <div v-if="error" class="error-message">
          <el-alert :title="error" type="error" show-icon :closable="false" />
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import authService from '../api/auth.service';
import { ElMessage } from 'element-plus';

const router = useRouter();
const route = useRoute();

const loginFormRef = ref(null);
const loginForm = ref({
  login_identifier: '',
  password: '',
});
const loading = ref(false);
const error = ref(null);

const loginRules = {
  login_identifier: [
    { required: true, message: '请输入用户名或邮箱', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6位', trigger: 'blur' }, // 根据实际后端规则调整
  ],
};

const handleLogin = async () => {
  if (!loginFormRef.value) return;
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      error.value = null;
      try {
        const response = await authService.login(loginForm.value);
        // 假设登录成功后，后端返回的数据在 response.data 中，并且包含 access_token
        localStorage.setItem('user_token', response.data.access_token);
        // 可选：存储用户信息到localStorage或Pinia store
        // localStorage.setItem('user_info', JSON.stringify(response.data.user));
        
        ElMessage.success('登录成功！');

        // 检查是否有重定向地址
        const redirectPath = route.query.redirect || '/';
        router.push(redirectPath);
      } catch (err) {
        console.error('登录失败:', err);
        error.value = err.message || '登录失败，请检查您的凭据或网络连接';
        if (err.errors) {
          // 如果后端返回了字段级别的错误
          let fieldErrors = [];
          for (const key in err.errors) {
            fieldErrors.push(...err.errors[key]);
          }
          error.value = fieldErrors.join('; ');
        }
        ElMessage.error(error.value);
      } finally {
        loading.value = false;
      }
    }
  });
};

const goToRegister = () => {
  router.push({ name: 'Register' });
};

</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 100px); /* 减去导航栏等高度 */
  background-color: #f0f2f5;
}

.login-card {
  width: 400px;
}

.card-header h2 {
  margin: 0;
  text-align: center;
}

.error-message {
  margin-top: 15px;
}
</style> 